# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jhkim

import random
import logging
from coin.exchange.base.order_gateway import OrderSide


class ExecScheduler(object):
  def __init__(self, *, quote_currency, product, target_qty, average_lot_size, min_lot_size):
    self.quote_currency = quote_currency
    self.product = product
    self.increasing_order_side = OrderSide.BUY
    self.decreasing_order_side = OrderSide.SELL
    self.target_qty = target_qty
    self.average_lot_size = average_lot_size
    self.min_lot_size = min_lot_size
    self.balance = None

  def update_balance(self, balance):
    self.balance = balance

  def get_remaining_qty(self):
    if self.balance is None:
      return None
    return self.target_qty - self.balance

  def get_lot_size(self):
    return max(self.min_lot_size, self.average_lot_size * random.uniform(0.5, 1.5))

  def get_order_side_and_qty(self):
    remaining_qty = self.get_remaining_qty()
    if remaining_qty is None or remaining_qty == 0:
      return (None, None)
    elif abs(remaining_qty) < self.min_lot_size:
      logging.warning("remaining_qty is too small: %s", remaining_qty)
      return (None, None)
    elif remaining_qty > 0:
      return self.increasing_order_side, min(self.get_lot_size(), remaining_qty)
    else:
      return self.decreasing_order_side, min(self.get_lot_size(), -remaining_qty)
